<?php

//生成uuid，唯一id
function guid(){
    if (function_exists('com_create_guid')){
        $uuid = com_create_guid();
    }else{
        mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
        $charid = strtoupper(md5(uniqid(rand(), true)));
        $hyphen = chr(45);// "-"
        $uuid = chr(123)// "{"
                .substr($charid, 0, 8).$hyphen
                .substr($charid, 8, 4).$hyphen
                .substr($charid,12, 4).$hyphen
                .substr($charid,16, 4).$hyphen
                .substr($charid,20,12)
                .chr(125);// "}"
    }
    $uuid = str_replace(array("-",'{','}'), '', $uuid);//去“-”,'{','}'
    $uuid = strtolower($uuid);//转换成小写
    return $uuid;
    
}

//生成唯一订单编号---20808349181
function gorderid(){
    $time = date('Hisymd',time());
    
    mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
    $charid = strtoupper(md5(uniqid(rand(), true)));
    $hyphen = chr(45);// "-"
    $uuid = chr(123)// "{"
            .substr($charid, 0, 8).$hyphen
            .substr($charid, 8, 4).$hyphen
            .substr($charid,12, 4).$hyphen
            .substr($charid,16, 4).$hyphen
            .substr($charid,20,12)
            .chr(125);// "}"
    $uuid = str_replace(array("-",'{','}'), '', $uuid);//去“-”,'{','}'
    $uuid = strtoupper($uuid);//转换成大写

    //以10精制形式转换8精制
    $base_uuid = base_convert($uuid,10,8);
    //截取后6位
    $last_uuid = $time."".substr($base_uuid,0,6);

    return $last_uuid;

}

//自定义打印方法
function timp($param){
    echo "<pre>";print_r($param);
}

//一般curl get请求
function curl_get($url,$debug=false){
    if(empty($url)) return $return = array('status'=>1001,'msg'=>'url is null','result'=>null);

    $start_time = microtime(true);
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    if($debug===true){
       $header = array();
       $platform_email = C(HTTP_BASIC_AUTH_DEBUG_USER);
       $platform_token = C(HTTP_BASIC_AUTH_DEBUG_USERTOKEN);
       $base64_auth_string = base64_encode($platform_email.":".$platform_token); 

       $header[] = 'Authorization:Basic '.$base64_auth_string;
       curl_setopt($curl, CURLOPT_HTTPHEADER,$header);
    }
    
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

    $return = array();
    $data = curl_exec($curl);
    if (curl_errno($curl)) {
        $return['status'] = 1002;
        $return['msg'] = curl_error($curl);
        $return['result'] = null;
    } else {
        $return['status'] = 200;
        $return['msg'] = 'OK';
        $return['result'] = $data;
        curl_close($curl);
    }

    $end_time = microtime(true);

    if($debug==true){
        $destination = C('LOG_PATH').'37degree_api_list/'.date('y_m_d').'.log';

        $message = "curl --insecure -X POST \"".$url."\" -u \"".$platform_email.":".$platform_token."\" -d ''";
        $message .="=>result:";
        $message .= $data;
        $message .="=>use_time:".round($end_time-$start_time,3)."s.\n";
    }else{
        $destination = C('LOG_PATH').'37degree_nomal_curl_get/'.date('y_m_d').'.log';

        $message = "curl: \"".$url."\"";
        $message .="=>result:";
        $message .= $data;
        $message .="=>use_time:".round($end_time-$start_time,3)."s.\n";
    }

    $level = \Think\Log::INFO;
    \Think\Log::write($message,$level,$type='',$destination);

    return $return;
}

//一般curl get请求
function curl_get_custom($url,$debug=false,$email,$token){
	
    if(empty($url)) return $return = array('status'=>1001,'msg'=>'url is null','result'=>null);

    $start_time = microtime(true);

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    if($debug===true){
       $header = array();
       $platform_email = C(HTTP_BASIC_AUTH_DEBUG_USER);
       $platform_token = C(HTTP_BASIC_AUTH_DEBUG_USERTOKEN);
       $base64_auth_string = base64_encode($platform_email.":".$platform_token); 
       
       $header[] = 'Authorization:Basic '.$base64_auth_string;
       curl_setopt($curl, CURLOPT_HTTPHEADER,$header);
    }else{
        $header = array();
        $base64_auth_string = base64_encode($email.":".$token); 
        $header[] = 'Authorization:Basic '.$base64_auth_string;
        
        curl_setopt($curl, CURLOPT_HTTPHEADER,$header);
    }
    
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

    $return = array();
    $data = curl_exec($curl);
    if (curl_errno($curl)) {
        $return['status'] = 1002;
        $return['msg'] = curl_error($curl);
        $return['result'] = null;
    } else {
        $curl_info = json_decode($data,true);
        if($curl_info['return_code']!=0){
           $return['status'] = $curl_info['return_code'];
           $return['msg'] = $curl_info['return_msg'];
           $return['result'] = $data; 
        }else{
            $return['status'] = 200;
            $return['msg'] = 'OK';
            $return['result'] = $data;
        }
        curl_close($curl);
    }

    $end_time = microtime(true);
    $destination = C('LOG_PATH').'37degree_api_list/'.date('y_m_d').'.log';

    if($debug==true){
        $message = "curl --insecure -X POST \"".$url."\" -u \"".$platform_email.":".$platform_token."\" -d ''";
    }else{
        $message = "curl --insecure -X POST \"".$url."\" -u \"".$email.":".$token."\" -d ''";
    }
    
    $message .="=>result:";
    $message .= $data;
    $message .="=>use_time:".round($end_time-$start_time,3)."s.\n";

    $level = \Think\Log::INFO;
    \Think\Log::write($message,$level,$type='',$destination);

    return $return;
}

function curl_post_custom($url,$param_array = array(),$debug=false,$email,$token){
    if(empty($url)) return $return = array('status'=>1001,'msg'=>'url is null','result'=>null);

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    
    if($debug===true){
       $header = array();
       $platform_email = C(HTTP_BASIC_AUTH_DEBUG_USER);
       $platform_token = C(HTTP_BASIC_AUTH_DEBUG_USERTOKEN);
       $base64_auth_string = base64_encode($platform_email.":".$platform_token); 

       $header[] = 'Authorization:Basic '.$base64_auth_string;
       curl_setopt($curl, CURLOPT_HTTPHEADER,$header);
    }else{
        $header = array();
        $base64_auth_string = base64_encode($email.":".$token); 

        $header[] = 'Authorization:Basic '.$base64_auth_string;
        curl_setopt($curl, CURLOPT_HTTPHEADER,$header);
    }

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    curl_setopt($curl, CURLOPT_POST,1);
    if(!empty($param_array)){
        $post_data = array();
        foreach ($param_array as $k=>$v){
            array_push($post_data, $k."=".urlencode($v)) ;
        }
        $post_data = implode("&", $post_data);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
    }

    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

    $return = array();
    $data = curl_exec($curl);

    if (curl_errno($curl)) {
        $return['status'] = 1002;
        $return['msg'] = curl_error($curl);
        $return['result'] = null;
    } else {
        $curl_info = json_decode($data,true);
        if($curl_info['return_code']!=0){
           $return['status'] = $curl_info['return_code'];
           $return['msg'] = $curl_info['return_msg'];
           $return['result'] = $data; 
        }else{
            $return['status'] = 200;
            $return['msg'] = 'OK';
            $return['result'] = $data;
        }
        curl_close($curl);
    }

    return $return;

}

//一般curl post请求
function curl_post($url,$param_array = array(),$debug=false){
    if(empty($url)) return $return = array('status'=>1001,'msg'=>'url is null','result'=>null);

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    
    if($debug===true){
       $header = array();
       $platform_email = C(HTTP_BASIC_AUTH_DEBUG_USER);
       $platform_token = C(HTTP_BASIC_AUTH_DEBUG_USERTOKEN);
       $base64_auth_string = base64_encode($platform_email.":".$platform_token); 

       $header[] = 'Authorization:Basic '.$base64_auth_string;
       curl_setopt($curl, CURLOPT_HTTPHEADER,$header);

       

    }

    if(!empty($param_array)){
        // $post_data = array();
        // foreach ($param_array as $k=>$v){
        //     array_push($post_data, $k."=".urlencode($v)) ;
        // }
        // $post_data = implode("&", $post_data);
        if(!is_array($param_array)){
            curl_setopt($curl, CURLOPT_POSTFIELDS, $param_array);
        }else{
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($param_array));
        }
    }

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    curl_setopt($curl, CURLOPT_POST,1);
    

    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

    $return = array();
    $data = curl_exec($curl);

    if (curl_errno($curl)) {
        $return['status'] = 1002;
        $return['msg'] = curl_error($curl);
        $return['result'] = null;
    } else {
        $return['status'] = 200;
        $return['msg'] = 'OK';
        $return['result'] = $data;
        curl_close($curl);
    }

    return $return;

}

//post curl(***特定于大后台交互，需要base64密钥 post***)
function dmp_curl_post($url,$param_array = array()){
    if(empty($url)) return $return = array('status'=>1001,'msg'=>'url is null','result'=>null);

    $start_time = microtime(true);
    $header = array();
    $platform_email = C(HTTP_BASIC_AUTH_USER);
    $platform_token = C(HTTP_BASIC_AUTH_USERTOKEN);
    $base64_auth_string = base64_encode($platform_email.":".$platform_token);

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $header[] = 'Authorization:Basic '.$base64_auth_string;
    curl_setopt($curl, CURLOPT_HTTPHEADER,$header);

    //curl_setopt($ch, CURLOPT_USERAGENT, $defined_vars['HTTP_USER_AGENT']);

    curl_setopt($curl, CURLOPT_POST,1);
    if(!empty($param_array)){
        $post_data = array();
        foreach ($param_array as $k=>$v){
            array_push($post_data, $k."=".urlencode($v)) ;
        }
        $post_data = implode("&", $post_data);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
    }
    //$post_data = array ("user" => "dmp_test@37degree.com","pwd" => "123456");
    // $post_data = "user=dmp_test@37degree.com&pwd=123456";
    // curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
    
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

    $return = array();
    $data = curl_exec($curl);

    if (curl_errno($curl)) {
        $return['status'] = 1002;
        $return['msg'] = curl_error($curl);
        $return['result'] = null;
    } else { 
        $curl_info = json_decode($data,true);
        if($curl_info['return_code']!=0){
           $return['status'] = $curl_info['return_code'];
           $return['msg'] = $curl_info['return_msg'];
           $return['result'] = $data; 
        }else{
            $return['status'] = 200;
            $return['msg'] = 'OK';
            $return['result'] = $data;
        }
        
        curl_close($curl);
    }
    $end_time = microtime(true);

    $destination = C('LOG_PATH').'37degree_api_list/'.date('y_m_d').'.log';

    $message = "curl --insecure -X POST \"".$url."\" -u \"".$platform_email.":".$platform_token."\" -d '".$post_data."'";
    $message .="=>result:";
    $message .= $data;
    $message .="=>use_time:".round($end_time-$start_time,3)."s.\n";

    $level = \Think\Log::INFO;
    \Think\Log::write($message,$level,$type='',$destination);

    return $return;

}

//搜索elasticsearch-支持put，delete，get，post多重方式的curl
function dmp_es_curlrequest($url,$data,$method='post'){
    $ch = curl_init(); //初始化CURL句柄 
    curl_setopt($ch, CURLOPT_URL, $url); //设置请求的URL
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); //设为TRUE把curl_exec()结果转化为字串，而不是直接输出 
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); //设置请求方式
     
    curl_setopt($ch,CURLOPT_HTTPHEADER,array("X-HTTP-Method-Override: $method"));//设置HTTP头信息
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置提交的字符串
    $document = curl_exec($ch);//执行预定义的CURL
    if(!curl_errno($ch)){
      $destination = C('LOG_PATH').'37degree_es_success/'.date('y_m_d').'.log'; 
      $info = curl_getinfo($ch);

      $message = "curl -X$method \"".$url."\" -d '".$data."'";
      $message .="=>result:ok \n";

    } else {
      $destination = C('LOG_PATH').'37degree_es_error/'.date('y_m_d').'.log'; 

      $message = "curl -X$method \"".$url."\" -d '".$data."'";
      $message .="=>result:error ".curl_error($ch)."\n";
    }

    $level = \Think\Log::INFO;
    \Think\Log::write($message,$level,$type='',$destination);

    curl_close($ch);
     
    return $document;
}

//ip检测
function is_ip($gonten){  
    $ip=explode(".",$gonten);  
    for($i=0;$i<count($ip);$i++) {  
        if($ip[$i]>255){  
        return(0);  
        }  
    }  
    return ereg("^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$",$gonten);  
}

//获取对应缓存key名称
function cache_key($name){
    //静态文件，放在缓存中
    
    //获取内存

}

/**
 * 邮件发送函数
 */
    function sendMail($to, $title, $content) {
        Vendor('PHPMailer.PHPMailerAutoload');     
        $mail = new PHPMailer(); //实例化
        $mail->IsSMTP(); // 启用SMTP
        $mail->CharSet='UTF-8';// 设置邮件的字符编码

        $mail->Host=C('MAIL_HOST'); //smtp服务器的名称（这里以QQ邮箱为例）
        $mail->SMTPAuth = C('MAIL_SMTPAUTH'); //启用smtp认证
        $mail->Username = C('MAIL_USERNAME'); //你的邮箱名
        $mail->Password = C('MAIL_PASSWORD') ; //邮箱密码
        $mail->From = C('MAIL_FROM'); //发件人地址（也就是你的邮箱地址）
        $mail->FromName = C('MAIL_FROMNAME'); //发件人姓名
        $mail->AddAddress($to,"尊敬的客户");
        $mail->WordWrap = 50; //设置每行字符长度
        $mail->IsHTML(C('MAIL_ISHTML')); // 是否HTML格式邮件
        $mail->CharSet=C('MAIL_CHARSET'); //设置邮件编码
        $mail->Subject =$title; //邮件主题
        $mail->Body = $content; //邮件内容
        $mail->AltBody = "这是一个纯文本的身体在非营利的HTML电子邮件客户端"; //邮件正文不支持HTML的备用显示
        //return($mail->Send());

        if(!$mail->Send())
        {
            return false;
            //echo "错误原因: " . $mail->ErrorInfo;
        }else{
            return true;
            //echo "发送成功了,嘛嘛再也不担心我不会发邮件了!";
        }
    }

    //获取激活邮件内容
    function getActivationContent ($url = '',$name = '尊敬的云途用户',$time = 24){
        $string = "";
        $string .= '<p>';
        $string .= ' <p class="MsoNormal">
                   <span style="font-size:14px;">'.$name.'，您好！</span>
         </p>';
        $string .= '<p>
                   <span style="font-size:14px;">&nbsp; &nbsp; 您已经成功注册云途数据帐号！</span><span></span>
         </p>';
        $string .= '<p>
                   <span style="font-size:14px;">&nbsp; &nbsp; <u><a href="'.$url.'" target="_blank"><span style="color:#E53333;">请点击这里立即完成激活</span></a></u></span><span></span>
         </p>';
        $string .= '<p>
                   <span style="font-size:12px;">如果上述文字点击无效，请将以下网址复制到浏览器地址栏打开（该链接</span><span style="font-size:12px;">'.$time.'</span><span style="font-size:12px;">小时后失效）：</span><span style="font-size:14px;line-height:1.5;">'.$url.'</span>
         </p>';
        $string .= ' <p>
                   <span style="font-size:14px;"><span style="font-size:14px;line-height:21px;">——————————————</span><span style="font-size:14px;line-height:21px;">——</span><span style="font-size:14px;line-height:21px;">—</span></span><span></span>
         </p>';
        $string .= '<p style="background:white;">
                   <strong><span style="font-size:12px;"></span></strong> <span style="font-size:12px;">http://www.37degree.com</span>
         </p>';
        $string .='<span style="color:#666666;font-size:12px;">&copy;2016 云途数据</span><span style="color:#666666;font-size:12px;"></span>';
        $string .= '</p>';

        return $string;

    }

    function resetPwdContent($url){
        $string = "";
        $string .='<p>
            <span style="font-size:14px;">尊敬的云途用户，您好！<br />
        &nbsp; &nbsp; &nbsp; 您提交了找回密码申请。请确认是您本人操作，如非本人操作请忽视此邮件。<br />
        </span><span></span> 
        </p>';
        $string .='<p>
            <span style="font-size:14px;">&nbsp; &nbsp; &nbsp;&nbsp;<u><a href="'.$url.'" target="_blank"><span style="color:#E53333;">点击找回密码</span></a></u></span> 
        </p>';
        $string .='<p>
            <span style="font-size:12px;">如果上述文字点击无效，请将以下网址复制到浏览器地址栏打开（该链接</span><span style="font-size:12px;">24</span><span style="font-size:12px;">小时后失效）：</span><span style="font-size:14px;line-height:1.5;">'.$url.'</span> 
        </p>';
        $string .='<p>
            <span style="font-size:14px;"><span style="font-size:14px;line-height:21px;">——————————————</span><span style="font-size:14px;line-height:21px;">——</span><span style="font-size:14px;line-height:21px;">—</span></span><span></span> 
        </p>';
        $string .='<p style="background:white;">
            <strong><span style="font-size:12px;"></span><span style="font-size:12px;">http://www.37degree.com</span> </strong>
        </p>';
        $string .='<strong><span style="color:#666666;font-size:12px;">&copy;2016 云途数据</span><span style="color:#666666;font-size:12px;"></span> 
        <p>
            <br />
        </p>
        </strong>';

        return $string;
    }

    //下架api邮件内容
    function apidownEmail($api_name,$service_name,$user_name){
        $string = "";
        $string .='<p>';
        $string .='<br />';
        $string .='</p>';
        $string .='<p class="MsoNormal">';
        $string .='<span style="font-size:14px;line-height:21px;">API 名称：'.$api_name.'</span>';
        $string .='</p>';
        $string .='<p class="MsoNormal">';
        $string .='<span style="font-size:14px;line-height:21px;"><span style="font-size:14px;line-height:21px;">所属服务：'.$service_name.'</span><br />';
        $string .='</span>';
        $string .='</p>';
        $string .='<p class="MsoNormal">';
        $string .='<span style="font-size:14px;line-height:21px;">服务商：'.$user_name.'</span>';
        $string .='</p>';
        $string .='<p class="MsoNormal">';
        $string .='<br />';
        $string .='</p>';
        $string .='<p>';
        $string .='<br />';
        $string .='</p>';

        return $string;
    } 

    //活动，数据征集邮件内容
    function activityCollectionEmailString($name='数据需求征集令',$data=array()){
        if(empty($data)) return false;
        
        $string = "";
        $string .= '<p>';
        $string .= ' <p class="MsoNormal">
                   <span style="font-size:14px;">'.$name.'</span>
         </p>';
        $string .= '<p>
                   <span style="font-size:14px;">数据需求：'.$data['content'].'</span><span></span>
         </p>';
         $string .= '<p>
                   <span style="font-size:14px;">姓名：'.$data['contact'].'</span><span></span>
         </p>';
         $string .= '<p>
                   <span style="font-size:14px;">手机：'.$data['tel'].'</span><span></span>
         </p>';
         $string .= '<p>
                   <span style="font-size:14px;">邮箱：'.$data['email'].'</span><span></span>
         </p>';
         $string .= '<p>
                   <span style="font-size:14px;">提交时间：'.date('Y-m-d H:i:s',time()).'</span><span></span>
         </p>';
        $string .= ' <p>
                   <span style="font-size:14px;"><span style="font-size:14px;line-height:21px;">——————————————</span><span style="font-size:14px;line-height:21px;">——</span><span style="font-size:14px;line-height:21px;">—</span></span><span></span>
         </p>';
        $string .= '<p style="background:white;">
                   <strong><span style="font-size:12px;"></span></strong> <span style="font-size:12px;">http://mall.37degree.com</span>
         </p>';
        $string .='<span style="color:#666666;font-size:12px;">&copy;2016 云途数据</span><span style="color:#666666;font-size:12px;"></span>';
        $string .= '</p>';

        return $string;
    }

    //session加密
    function myEncrption($string = null){
        if(empty($string)) return null;

        $new_string = md5 (base64_encode($string) );
        return $new_string;
    }

    // $string： 明文 或 密文  
    // $operation：DECODE表示解密,其它表示加密  
    // $key： 密匙  
    // $expiry：密文有效期  
    function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
        
        // 动态密匙长度，相同的明文会生成不同密文就是依靠动态密匙  
        $ckey_length = 4;  
           
        // 密匙  
        $key = md5($key ? $key : $GLOBALS['discuz_auth_key']);  
           
        // 密匙a会参与加解密  
        $keya = md5(substr($key, 0, 16));  
        // 密匙b会用来做数据完整性验证  
        $keyb = md5(substr($key, 16, 16));  
        // 密匙c用于变化生成的密文  
        $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : ''; 

        // 参与运算的密匙  
        $cryptkey = $keya.md5($keya.$keyc);
        $key_length = strlen($cryptkey);  

        // 明文，前10位用来保存时间戳，解密时验证数据有效性，10到26位用来保存$keyb(密匙b)，解密时会通过这个密匙验证数据完整性  
        // 如果是解码的话，会从第$ckey_length位开始，因为密文前$ckey_length位保存 动态密匙，以保证解密正确  
        $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;

        $string_length = strlen($string);

        $result = '';  
        $box = range(0, 255);  
        $rndkey = array();  
        // 产生密匙簿  
        for($i = 0; $i <= 255; $i++) {  
            $rndkey[$i] = ord($cryptkey[$i % $key_length]);  
        }  
        // 用固定的算法，打乱密匙簿，增加随机性，好像很复杂，实际上对并不会增加密文的强度  
        for($j = $i = 0; $i < 256; $i++) {  
            $j = ($j + $box[$i] + $rndkey[$i]) % 256;  
            $tmp = $box[$i];  
            $box[$i] = $box[$j];  
            $box[$j] = $tmp;  
        }  
        // 核心加解密部分  
        for($a = $j = $i = 0; $i < $string_length; $i++) {  
            $a = ($a + 1) % 256;  
            $j = ($j + $box[$a]) % 256;  
            $tmp = $box[$a];  
            $box[$a] = $box[$j];  
            $box[$j] = $tmp;  
            // 从密匙簿得出密匙进行异或，再转成字符  
            $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));  
        }

        if($operation == 'DECODE') {  
            // substr($result, 0, 10) == 0 验证数据有效性  
            // substr($result, 0, 10) - time() > 0 验证数据有效性  
            // substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16) 验证数据完整性  
            // 验证数据有效性，请看未加密明文的格式  
            if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
                return substr($result, 26);
            } else {
                return '';  
            }  
        } else {  
            // 把动态密匙保存在密文里，这也是为什么同样的明文，生产不同密文后能解密的原因  
            // 因为加密后的密文可能是一些特殊字符，复制过程可能会丢失，所以用base64编码  
            return $keyc.str_replace('=', '', base64_encode($result));  
        }  
    }

    //加密算法
    function encrypt($data, $key)  
    {  
        $key    =   md5($key);  
        $x      =   0;  
        $len    =   strlen($data);  
        $l      =   strlen($key);  
        for ($i = 0; $i < $len; $i++)  
        {  
            if ($x == $l)   
            {  
                $x = 0;  
            }  
            $char .= $key{$x};  
            $x++;  
        }  
        for ($i = 0; $i < $len; $i++)  
        {  
            $str .= chr(ord($data{$i}) + (ord($char{$i})) % 256);  
        }  
        return base64_encode($str);  
    }  

    //解密算法
    function decrypt($data, $key)  
    {  
        $key = md5($key);  
        $x = 0;  
        $data = base64_decode($data);  
        $len = strlen($data);  
        $l = strlen($key);  
        for ($i = 0; $i < $len; $i++)  
        {  
            if ($x == $l)   
            {  
                $x = 0;  
            }  
            $char .= substr($key, $x, 1);  
            $x++;  
        }  
        for ($i = 0; $i < $len; $i++)  
        {  
            if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1)))  
            {  
                $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));  
            }  
            else  
            {  
                $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));  
            }  
        }  
        return $str;  
    } 
    
    //手机号判断
    function checkMobile($mobile){
        if(empty($mobile)) return false;
        if(preg_match("/^1\d{10}$/", $mobile)){
            return true;
        }
        return false;
    }

    //基本网址判断
    function checkWebsite($url){
        if(empty($url)) return false;
        $preg = "/^https?:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/";
        
        if(preg_match($preg, $url)){
            return true;
        }
        return false;
    }

    //基本网址判断
    function checkDomain($url){
        if(empty($url)) return false;
        $preg = "/^[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/";
        if(preg_match($preg, $url)){
            return true;
        }
        return false;
    }

    //服务、API英文名判断
    function checkEnName($name){
        if(empty($name)) return false;
        $preg = "/^[a-zA-Z][a-zA-Z0-9_]{1,29}$/";
        if(preg_match($preg, $name)){
            return true;
        }
        return false;
    }
    
     //用户名判断
    function checkUserName($name){
        if(empty($name)) return false;
        $preg = "/^[a-zA-Z][a-zA-Z0-9_]{3,20}$/";
        
        if(preg_match($preg, $name)){
            return true;
        }
        return false;
    }
     //密码判断
    function checkPasswd($name){
        if(empty($name)) return false;
        $preg = "/^[\w~!@#$%^&*]{6,16}$/";
        
        if(preg_match($preg, $name)){
            return true;
        }
        return false;
    }
    
    //email判断
    function checkEmail($name){
        if(empty($name)) return false;
        
        $preg = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i"; 
        if(preg_match($preg, $name)){
            return true;
        }
        return false;
    }
    
    function checkIdcard($idcard){
    	$preg="/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|[X|x])$/";
        if(preg_match($preg, $idcard)){
            return true;
        }
        return false;    	
    }
    
    function checkServiceApiName($name){
        if(empty($name)) return false;
        
        $preg = "/^[\p{Han}\w]{1,10}$/u"; 
        if(preg_match($preg, $name)){
            return true;
        }
        return false;
    }
    
    //对二维数组去重
    function assoc_unique($arr, $key) {
        $tmp_arr = array();
        foreach ($arr as $k => $v) {
            if (in_array($v[$key], $tmp_arr)) {//搜索$v[$key]是否在$tmp_arr数组中存在，若存在返回true
                unset($arr[$k]);
            } else {
                $tmp_arr[] = $v[$key];
            }
        }
        // sort($arr); //sort函数对数组进行排序
        return $arr;
    }

    function tp_curl_multi(){
        $mh = curl_multi_init(); //返回一个新cURL批处理句柄
        for ($i = 0; $i < $max_size; $i++)
        {
            $ch = curl_init();  //初始化单个cURL会话
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_URL, 'http://www.zhihu.com/people/' . $user_list[$i] . '/about');
            curl_setopt($ch, CURLOPT_COOKIE, self::$user_cookie);
            curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.130 Safari/537.36');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            $requestMap[$i] = $ch;
            curl_multi_add_handle($mh, $ch);  //向curl批处理会话中添加单独的curl句柄
        }
     
        $user_arr = array();
        do {
            //运行当前 cURL 句柄的子连接
            while (($cme = curl_multi_exec($mh, $active)) == CURLM_CALL_MULTI_PERFORM);
     
            if ($cme != CURLM_OK) {
                break;
            }
            
            //获取当前解析的cURL的相关传输信息
            while ($done = curl_multi_info_read($mh))
            {
                $info = curl_getinfo($done['handle']);
                $tmp_result = curl_multi_getcontent($done['handle']);
                $error = curl_error($done['handle']);
     
                $user_arr[] = array_values(getUserInfo($tmp_result));
     
                //保证同时有$max_size个请求在处理
                if ($i < sizeof($user_list) && isset($user_list[$i]) && $i < count($user_list))
                {
                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_HEADER, 0);
                    curl_setopt($ch, CURLOPT_URL, 'http://www.zhihu.com/people/' . $user_list[$i] . '/about');
                    curl_setopt($ch, CURLOPT_COOKIE, self::$user_cookie);
                    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.130 Safari/537.36');
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                    $requestMap[$i] = $ch;
                    curl_multi_add_handle($mh, $ch);
     
                    $i++;
                }
     
                curl_multi_remove_handle($mh, $done['handle']);
            }
     
            if ($active)
                curl_multi_select($mh, 10);
        } while ($active);
     
        curl_multi_close($mh);
        return $user_arr;
    }

    //处理分类结构
    function recursionWithCategoroy($all_category,$pid=0){
        //格式
        // array(
        //     array( 'id'=>1,'name'=>'1','pid'=>0,'children'=>array('id'=>11,'name'=>'11','pid'=>1,'children'=>array()) ),
        //     array( 'id'=>2,'name'=>'2','pid'=>0,'children'=>array('id'=>22,'name'=>'22','pid'=>2,'children'=>array()) ),
        //     array( 'id'=>3,'name'=>'3','pid'=>0,'children'=>array('id'=>33,'name'=>'33','pid'=>3,'children'=>array()) ),
        // )
        $category_array = array();
        foreach ($all_category as $k=>$category){
            $category_pid = $category['pid'];
            $category_id = $category['id'];

            if($category_pid==0){
                if(!isset($category_array[$category_id])){
                    $category_array[$category_id] = array_merge($category,array('children'=>''));   
                }else{
                    $category_array[$category_id] = array_merge( $category_array[$category_id] , $category );
                }
            }else{
                //非顶级pid时，寻找顶级信息
                $category_array[$category_pid]['children'][$category_id] = $category;

            }
        }

        $return_array = array();
        if(!empty($category_array)){
        	$num = 1;
            foreach ($category_array as $key=>$val){
                $return_array[$num."-".$val['id']] = $val;
                $num++;
            }    
        } 
        
        return $return_array;
        // timp($return_array);die;
    }
    
    
